package com.devfest.wishmaster.db;

import java.util.ArrayList;
import java.util.List;

import com.devfest.wishmaster.model.Comment;
import com.devfest.wishmaster.model.User;
import com.devfest.wishmaster.model.WishItem;
import com.devfest.wishmaster.model.WishList;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "HRDB.sqlite";

	private static final int DATABASE_VERSION = 1;

	private Dao<Comment, Integer> commentDao;
	private Dao<User, Integer> userDao;
	private Dao<WishItem, Integer> wishItemDao;
	private Dao<WishList, Integer> wishListDao;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase database,
			ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, Comment.class);
			TableUtils.createTable(connectionSource, User.class);
			TableUtils.createTable(connectionSource, WishItem.class);
			TableUtils.createTable(connectionSource, WishList.class);
		} catch (Exception e) {
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase database,
			ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {
			List<String> allSql = new ArrayList<String>();
			switch (oldVersion) {
			case 1:
				// allSql.add("alter table AdData add column `new_col` VARCHAR");
				// allSql.add("alter table AdData add column `new_col2` VARCHAR");
			}
			for (String sql : allSql) {
				database.execSQL(sql);
			}
		} catch (Exception e) {
		}
	}

	public Dao<Comment, Integer> getCommentDao() {
		if (commentDao == null) {
			try {
				commentDao = getDao(Comment.class);
			} catch (Exception e) {
			}
		}
		return commentDao;
	}

	public Dao<User, Integer> getUserDao() {
		if (commentDao == null) {
			try {
				userDao = getDao(User.class);
			} catch (Exception e) {
			}
		}
		return userDao;
	}

	public Dao<WishItem, Integer> getWishItemDao() {
		if (wishItemDao == null) {
			try {
				wishItemDao = getDao(WishItem.class);
			} catch (Exception e) {
			}
		}
		return wishItemDao;
	}

	public Dao<WishList, Integer> getWishListDao() {
		if (wishListDao == null) {
			try {
				wishListDao = getDao(WishList.class);
			} catch (Exception e) {
				Log.e("DevFest", e.toString());
			}
		}
		return wishListDao;
	}
}